export const extractPayload = <T = any>(response: any): T => {
  if (response?.data !== undefined) {
    return response.data as T
  }
  return response as T
}

const normalizeCodeValue = (payload: any) => {
  if (!payload || typeof payload !== 'object') return undefined
  return (
    payload.code ??
    payload.Code ??
    payload.status ??
    payload.Status ??
    payload.resultCode ??
    payload.ResultCode ??
    payload.success ??
    payload.Success
  )
}

const successNumberSet = new Set([200, 0, 1])
const successStringSet = new Set(['200', '0', '1', 'success', 'SUCCESS', 'Success'])

export const isRequestSuccess = (payload: any): boolean => {
  if (!payload) return false

  if (payload.success === true || payload.Success === true) {
    return true
  }

  const code = normalizeCodeValue(payload)
  if (typeof code === 'number') {
    return successNumberSet.has(code)
  }
  if (typeof code === 'string') {
    return successStringSet.has(code)
  }
  if (typeof code === 'boolean') {
    return code
  }

  return false
}

export const getResponseMessage = (payload: any, fallback: string): string => {
  if (!payload || typeof payload !== 'object') return fallback
  return (
    payload.msg ??
    payload.Msg ??
    payload.message ??
    payload.Message ??
    payload.resultMessage ??
    payload.ResultMessage ??
    fallback
  )
}

export const getErrorMessage = (error: any, fallback: string): string => {
  if (!error) return fallback

  const responseData =
    error.response?.data ??
    error.data ??
    error.body ??
    error

  if (responseData && typeof responseData === 'object') {
    const msg = getResponseMessage(responseData, '')
    if (msg) {
      return msg
    }
  }

  if (typeof error.message === 'string' && error.message) {
    return error.message
  }

  return fallback
}

